import { MutationTree } from "vuex";
import { State, TodoItem } from "./state";

export enum MutationType {
  CreateItem = "CREATE_ITEM",
  SetItem = "SET_ITEM",
  CompleteItem = "COMPLETE_ITEM",
  SetLoading = "SET_LOADING"
}

export type Mutations = {
  [MutationType.CreateItem](state: State, item: TodoItem): void;
  [MutationType.SetItem](state: State, items: Array<TodoItem>): void;
  [MutationType.CompleteItem](
    state: State,
    items: Partial<TodoItem> & { id: number }
  ): void;
  [MutationType.SetLoading](state: State, value: boolean): void;
};

export const mutations: MutationTree<State> & Mutations = {
  [MutationType.CreateItem](state, item) {
    state.todoList.unshift(item);
  },
  [MutationType.SetItem](state, items) {
    state.todoList = items;
  },
  [MutationType.CompleteItem](state, item) {
    const targetItemIndex = state.todoList.findIndex(s => s.id === item.id);
    if (targetItemIndex !== -1) {
      state.todoList[targetItemIndex] = {
        ...state.todoList[targetItemIndex],
        ...item
      };
    }
  },
  [MutationType.SetLoading](state, value) {
    state.loading = value;
  }
};
